﻿using Pseudogenerator.Common.ViewModels;
using Pseudogenerator.Common.ViewModels.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Excel = Microsoft.Office.Interop.Excel;

namespace Pseudogenerator.Views.WPF
{
    /// <summary>
    /// Lógica de interacción para MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            var dctx =  new MainViewModel(new External.WpfCommandManager());
            dctx.WorkSpaces.ForEach(w => w.ActionCommands.Add(ExportToExcelCommand));

            mainControl.DataContext = dctx;
        }

        private RelayCommand exportToExcelCommand = null;
        public RelayCommand ExportToExcelCommand
        {
            get
            {
                if (exportToExcelCommand == null)
                    exportToExcelCommand = new RelayCommand("Exportar a Excel", p => ExportToExcel());

                return exportToExcelCommand;
            }
        }
        
        void ExportToExcel()
        {
            var Results = mainControl.SelectedNumbers;

            Excel.Application oXL;
            Excel._Workbook oWB;
            Excel._Worksheet oSheet;
            try
            {
                oXL = new Excel.Application();
                oWB = (Excel._Workbook)(oXL.Workbooks.Add(System.Reflection.Missing.Value));
                oSheet = (Excel._Worksheet)oWB.ActiveSheet;

                int i = 1;
                oSheet.Cells[i, 1] = "n";
                oSheet.Cells[i, 2] = "Xn";
                oSheet.Cells[i, 3] = "Número Uniforme";
                foreach (var item in Results)
                {
                    i++;
                    oSheet.Cells[i, 1] = item.n;
                    oSheet.Cells[i, 2] = item.Xn;
                    oSheet.Cells[i, 3] = item.Uniform;
                }

                var oRng = oSheet.get_Range("C1", "C1");
                oRng.EntireColumn.AutoFit();

                oXL.Visible = true;
                oXL.UserControl = true;
            }
            catch (Exception theException)
            {
                string errorMessage;
                errorMessage = "Error: ";
                errorMessage = string.Concat(errorMessage, theException.Message);
                errorMessage = string.Concat(errorMessage, " Line: ");
                errorMessage = string.Concat(errorMessage, theException.Source);
                throw new Exception(errorMessage);
            }
        }
    }
}
